package com.tuanzi.loan.business.service.miniApps.articleLibrary.impl;

import java.util.ArrayList;
import java.util.Date;
import java.util.List;

import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.Page;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.retry.RetryException;
import org.springframework.retry.annotation.Retryable;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import com.tuanzi.loan.business.entity.miniApps.articleLibrary.MiniAppsArticle;
import com.tuanzi.loan.business.entity.miniApps.articleLibrary.MiniAppsArticleRecord;
import com.tuanzi.loan.business.entity.miniApps.articleLibrary.MiniAppsArticleRelations;
import com.tuanzi.loan.business.entity.miniApps.articleLibrary.MiniAppsArticleUrl;
import com.tuanzi.loan.business.entity.miniApps.articleLibrary.MiniAppsRelation;
import com.tuanzi.loan.business.enums.MiniAppsRelationTypeEnum;
import com.tuanzi.loan.business.repository.miniApps.articleLibrary.HealthHeadlineRepository;
import com.tuanzi.loan.business.repository.miniApps.articleLibrary.MiniAppsArticleRecordRepository;
import com.tuanzi.loan.business.repository.miniApps.articleLibrary.MiniAppsArticleRelationsRepository;
import com.tuanzi.loan.business.repository.miniApps.articleLibrary.MiniAppsArticleRepository;
import com.tuanzi.loan.business.repository.miniApps.articleLibrary.MiniAppsArticleUrlRepository;
import com.tuanzi.loan.business.repository.miniApps.articleLibrary.MiniAppsRelationRepository;
import com.tuanzi.loan.business.service.miniApps.articleLibrary.HealthHeadlineService;
import com.tuanzi.loan.core.aspect.Debug;
import com.tuanzi.loan.core.vo.PageSearcher;
import com.tuanzi.loan.vo.request.miniApps.articleLibrary.HealthHeadlineRequest;
import com.tuanzi.loan.vo.response.miniApps.articleLibrary.HealthHeadlineResponse;
import com.tuanzi.loan.vo.view.miniApps.articleLibrary.HealthHeadlineInfoView;
import com.tuanzi.loan.vo.view.miniApps.articleLibrary.MiniAppsArticleUrlVo;
import com.tuanzi.server.loan_base.constant.LoanRedisKey;
import com.tuanzi.server.loan_base.constant.miniapps.article.ArticleConstant;

@Debug
@Service
@Transactional
@Retryable(value = { RetryException.class })
public class HealthHeadlineServiceImpl implements HealthHeadlineService{
	
	private static String imgHtmlTabModel = "<img src='##IMG_URL##'></img>"; // 图片Html标签模板
	private static String videoHtmlTabModel = "<video src='##VIDEO_URL##' controls></video>"; // 视频Html标签模板
	
	@Autowired
	private StringRedisTemplate stringRedisTemplate;
	@Autowired
	private HealthHeadlineRepository healthHeadlineRepository;
	@Autowired
	private MiniAppsArticleRepository miniAppsArticleRepository;
	@Autowired
	private MiniAppsArticleUrlRepository miniAppsArticleUrlRepository;
	@Autowired
	private MiniAppsArticleRelationsRepository miniAppsArticleRelationsRepository;
	@Autowired
	private MiniAppsRelationRepository miniAppsRelationRepository;
	@Autowired
	private MiniAppsArticleRecordRepository miniAppsArticleRecordRepository;
	
	public void deleteArticle(Long articleId) {
		List<MiniAppsArticleUrl> urlList = miniAppsArticleUrlRepository.findByArticleId(articleId);
		if(urlList != null) {
			for(MiniAppsArticleUrl url : urlList) {
				miniAppsArticleUrlRepository.delete(url.getId());
			}
		}
		
		List<MiniAppsArticleRelations> relationList = miniAppsArticleRelationsRepository.findByArticleId(articleId);
		if(relationList != null) {
			for(MiniAppsArticleRelations relations : relationList) {
				miniAppsArticleRelationsRepository.delete(relations.getId());
			}
		}
		
		miniAppsArticleRepository.delete(articleId);
	}
	
	public void onlineArticle(Long articleId) {
		MiniAppsArticle article = miniAppsArticleRepository.findOne(articleId);
		if(article.getOnlineTime() == null) {
			article.setOnlineTime(new Date());
		}
		article.setOnlineStatus(1);
		miniAppsArticleRepository.save(article);
	}
	
	public void offlineArticle(Long articleId) {
		MiniAppsArticle article = miniAppsArticleRepository.findOne(articleId);
		article.setOnlineStatus(0);
		miniAppsArticleRepository.save(article);
	}
	
	
	public HealthHeadlineInfoView loadHealthHeadlineInfoView(Long articleId) {
		HealthHeadlineInfoView view = new HealthHeadlineInfoView();
		MiniAppsArticle miniAppsArticle = miniAppsArticleRepository.findOne(articleId);
		BeanUtils.copyProperties(miniAppsArticle, view);
		
		// 查找对应所属的标签、小程序、推荐状态
		view.setSelectedTabList(getSelectedTabList(articleId));
		view.setSelectedMiniAppsList(getSelectedMiniAppsList(articleId));
		view.setRecommendStatus(getRecommendStatus(articleId));
		
		// 查找主图链接
		view.setRecommendMainImage(getMainImgVo(articleId));
		view.setContentImgList(getContentImgVoList(articleId));
		view.setContentVideoList(getContentVideoVoList(articleId));
		
		return view;
	}
	
	public MiniAppsArticleUrlVo saveContentConfImg(HealthHeadlineInfoView view, String imgUrl) {
		MiniAppsArticleUrl model = new MiniAppsArticleUrl();
		model.setArticleId(view.getId());
		model.setType(ArticleConstant.ARTICLE_URL_TYPE_CONTENT_IMAGE);
		model.setUploadUrl(imgUrl);
		miniAppsArticleUrlRepository.save(model);
		
		MiniAppsArticleUrlVo vo = new MiniAppsArticleUrlVo();
    	BeanUtils.copyProperties(model, vo);
    	String htmlTab = imgHtmlTabModel.replace("##IMG_URL##", vo.getUploadUrl());
		vo.setUploadUrlHtmlTab(htmlTab);
		
		return vo;
	}
	
	public MiniAppsArticleUrlVo saveContentConfVideo(HealthHeadlineInfoView view, String videoUrl) {
		MiniAppsArticleUrl model = new MiniAppsArticleUrl();
		model.setArticleId(view.getId());
		model.setType(ArticleConstant.ARTICLE_URL_TYPE_VIDEO);
		model.setUploadUrl(videoUrl);
		miniAppsArticleUrlRepository.save(model);
		
		MiniAppsArticleUrlVo vo = new MiniAppsArticleUrlVo();
    	BeanUtils.copyProperties(model, vo);
    	String htmlTab = videoHtmlTabModel.replace("##VIDEO_URL##", vo.getUploadUrl());
		vo.setUploadUrlHtmlTab(htmlTab);
		
		return vo;
	}
	
	public void saveOrUpdHeadlineInfo(HealthHeadlineInfoView view) {
		Long articleId = view.getId();
		
		// 更新文章内容
		MiniAppsArticle miniAppsArticle = miniAppsArticleRepository.findOne(articleId);
		BeanUtils.copyProperties(view, miniAppsArticle);
		miniAppsArticle.setUpdateTime(new Date());
		miniAppsArticleRepository.save(miniAppsArticle);
		
		// 更新推荐主图
		updateRecommendMainImage(view);
		
		// 更新文章类型关系
		delOrgRelationAndSave(view);
		
		// 删除缓存
		stringRedisTemplate.delete(LoanRedisKey.getArticleDetailKey(articleId));
	}
	
	/**
	 * 获得内容视频list
	 * @param articleId
	 * @return
	 */
	private List<MiniAppsArticleUrlVo> getContentVideoVoList(Long articleId) {
		List<MiniAppsArticleUrl> confVideoList = miniAppsArticleUrlRepository.findByArticleIdAndType(articleId, ArticleConstant.ARTICLE_URL_TYPE_VIDEO);
		if(confVideoList == null || confVideoList.size() == 0) {
			return null;
		}
		
		List<MiniAppsArticleUrlVo> voList = new ArrayList<MiniAppsArticleUrlVo>();
		for(MiniAppsArticleUrl model : confVideoList) {
			MiniAppsArticleUrlVo vo = new MiniAppsArticleUrlVo();
			BeanUtils.copyProperties(model, vo);
			String htmlTab = videoHtmlTabModel.replace("##VIDEO_URL##", vo.getUploadUrl());
			vo.setUploadUrlHtmlTab(htmlTab);
			voList.add(vo);
		}
		return voList;
	}
	
	/**
	 * 获得内容图片list
	 * @param articleId
	 * @return
	 */
	private List<MiniAppsArticleUrlVo> getContentImgVoList(Long articleId) {
		List<MiniAppsArticleUrl> confImgList = miniAppsArticleUrlRepository.findByArticleIdAndType(articleId, ArticleConstant.ARTICLE_URL_TYPE_CONTENT_IMAGE);
		if(confImgList == null || confImgList.size() == 0) {
			return null;
		}
		
		List<MiniAppsArticleUrlVo> voList = new ArrayList<MiniAppsArticleUrlVo>();
		for(MiniAppsArticleUrl model : confImgList) {
			MiniAppsArticleUrlVo vo = new MiniAppsArticleUrlVo();
			BeanUtils.copyProperties(model, vo);
			String htmlTab = imgHtmlTabModel.replace("##IMG_URL##", vo.getUploadUrl());
			vo.setUploadUrlHtmlTab(htmlTab);
			voList.add(vo);
		}
		return voList;
	}
	
	/**
	 * 获得主图
	 */
	private MiniAppsArticleUrlVo getMainImgVo(Long articleId) {
		MiniAppsArticleUrlVo vo = new MiniAppsArticleUrlVo();
		List<MiniAppsArticleUrl> mainImgList = miniAppsArticleUrlRepository.findByArticleIdAndType(articleId, 3);
		if(mainImgList == null || mainImgList.size() == 0) {
			return vo;
		}
		
		BeanUtils.copyProperties(mainImgList.get(0), vo);
		return vo;
	}
	
	/**
	 * 获取文章的推荐状态
	 * @param articleId
	 * @return
	 */
	private int getRecommendStatus(Long articleId) {
		List<String> typeList = new ArrayList<String>();
		typeList.add(MiniAppsRelationTypeEnum.SORT.getValue());
		List<MiniAppsArticleRelations> relationList = healthHeadlineRepository.selectRelationByArticleIdAndTypeList(articleId,typeList);
		if(relationList == null || relationList.size() == 0) {
			return 0;
		} else {
			return relationList.get(0).getStatus();
		}
	}
	
	/**
	 * 删除原有推荐状态，保存当前推荐状态
	 */
	public void saveRecommendStatus(Long articleId , int recommendStatus) {
		List<MiniAppsRelation> relationTypeList = miniAppsRelationRepository.findByType(MiniAppsRelationTypeEnum.SORT.getValue());
		List<MiniAppsArticleRelations> relationList = miniAppsArticleRelationsRepository
				.findByArticleIdAndRelationId(articleId, relationTypeList.get(0).getId().intValue());
		
		MiniAppsArticleRelations relation = null;
		if(relationList == null || relationList.size() == 0) {
			relation = new MiniAppsArticleRelations();
			relation.setArticleId(articleId);
			relation.setRelationId(relationTypeList.get(0).getId().intValue());
		} else {
			relation = relationList.get(0);
		}
		relation.setStatus(recommendStatus);
		miniAppsArticleRelationsRepository.save(relation);
	}
	
	/**
	 * 删除所有原先文章类型关系然后保存新的类型关系
	 */
	private void delOrgRelationAndSave(HealthHeadlineInfoView view) {
		// 删除原有类型关系
		List<String> typeList = new ArrayList<String>();
		typeList.add(MiniAppsRelationTypeEnum.TAB.getValue());
		typeList.add(MiniAppsRelationTypeEnum.MINI_APPS.getValue());
		typeList.add(MiniAppsRelationTypeEnum.SORT.getValue());
		List<MiniAppsArticleRelations> relationList = healthHeadlineRepository.selectRelationByArticleIdAndTypeList(view.getId(),typeList);
		for(MiniAppsArticleRelations relation : relationList) {
			miniAppsArticleRelationsRepository.delete(relation.getId());
		}
		
		// 保存标签关联关系
		List<String> selectedTabList = view.getSelectedTabList();
		if(selectedTabList != null) {
			for(int i=0; i<selectedTabList.size(); i++) {
				Long relationId = Long.valueOf(selectedTabList.get(i));
				MiniAppsArticleRelations relation = new MiniAppsArticleRelations();
				relation.setArticleId(view.getId());
				relation.setRelationId(relationId.intValue());
				relation.setStatus(1);
				miniAppsArticleRelationsRepository.save(relation);
			}
		}
		// 保存小程序关联关系
		List<String> selectedMiniAppsList = view.getSelectedMiniAppsList();
		if(selectedMiniAppsList != null) {
			for(int i=0; i<selectedMiniAppsList.size(); i++) {
				Long relationId = Long.valueOf(selectedMiniAppsList.get(i));
				MiniAppsArticleRelations relation = new MiniAppsArticleRelations();
				relation.setArticleId(view.getId());
				relation.setRelationId(relationId.intValue());
				relation.setStatus(1);
				miniAppsArticleRelationsRepository.save(relation);
			}
		}
		
		// 保存推荐状态
		List<MiniAppsRelation> relationTypeList = miniAppsRelationRepository.findByType(MiniAppsRelationTypeEnum.SORT.getValue());
		MiniAppsArticleRelations relation = new MiniAppsArticleRelations();
		relation.setArticleId(view.getId());
		relation.setRelationId(relationTypeList.get(0).getId().intValue());
		relation.setOnlineTime(view.getRecommendTime());
		relation.setStatus(view.getRecommendStatus());
		miniAppsArticleRelationsRepository.save(relation);
	}
	
	/**
	 * 更新推荐主图
	 * @param view
	 */
	private void updateRecommendMainImage(HealthHeadlineInfoView view) {
		MiniAppsArticleUrl articleUrl = miniAppsArticleUrlRepository.findByArticleIdAndType(view.getId(), 3).get(0);
		articleUrl.setUploadUrl(view.getRecommendMainImage().getUploadUrl());
		miniAppsArticleUrlRepository.save(articleUrl);
	}
	
	
	/**
	 * 获取文章所属的标签
	 * @param articleId
	 * @return
	 */
	private List<String> getSelectedTabList(Long articleId) {
		List<MiniAppsRelation> relationList = healthHeadlineRepository.getTabListOfArticle(articleId);
		if(relationList == null || relationList.size() == 0) {
			return null;
		}
		
		List<String> selectedTabList = new ArrayList<String>(); 
		for(MiniAppsRelation relation : relationList) {
			selectedTabList.add(String.valueOf(relation.getId()));
		}
		return selectedTabList;
	}
	
	/**
	 * 获取文章所属的小程序
	 * @param articleId
	 * @return
	 */
	private List<String> getSelectedMiniAppsList(Long articleId) {
		List<MiniAppsRelation> relationList = healthHeadlineRepository.getMiniAppsListOfArticle(articleId);
		if(relationList == null || relationList.size() == 0) {
			return null;
		}
		
		List<String> selectedMiniAppsList = new ArrayList<String>(); 
		for(MiniAppsRelation relation : relationList) {
			selectedMiniAppsList.add(String.valueOf(relation.getId()));
		}
		return selectedMiniAppsList;
	}

	@Override
	public Page<HealthHeadlineResponse> list(
			PageSearcher<HealthHeadlineRequest> pageSearcher) {
		Page<HealthHeadlineResponse> pageList = healthHeadlineRepository.getListPage(pageSearcher.getSearchCondition(), pageSearcher.getPageable());
		
		List<String> typeList = new ArrayList<String>();
		typeList.add(MiniAppsRelationTypeEnum.SORT.getValue());
		
		List<HealthHeadlineResponse> list = pageList.getContent();
		if(list != null) {
			for(HealthHeadlineResponse response : list) {
				Long articleId = (Long) response.getId();
				List<MiniAppsArticleRelations> relationList = healthHeadlineRepository.selectRelationByArticleIdAndTypeList(articleId,typeList);
				if(relationList == null || relationList.size() == 0) {
					response.setRecommendStatus(0);
				} else {
					response.setRecommendStatus(relationList.get(0).getStatus());
				}
				
				List<MiniAppsArticleUrl> mainImageList = miniAppsArticleUrlRepository.findByArticleIdAndType(articleId,3);
				if(mainImageList != null && mainImageList.size() != 0) {
					response.setRecommendMainImage(mainImageList.get(0).getUploadUrl());
				}
			}
		}
		return pageList;
	}
	
	@Override
	public List<MiniAppsRelation> getAdvertiseList() {
		return healthHeadlineRepository.getAdvertiseList();
	}

	@Override
	public List<MiniAppsRelation> getTabList() {
		return healthHeadlineRepository.getTabList();
	}

	@Override
	public List<MiniAppsRelation> getMiniAppsList() {
		return healthHeadlineRepository.getMiniAppsList();
	}
	
	@Override
	public List<MiniAppsArticle> getSourceList() {
		return healthHeadlineRepository.getSourceList();
	}

	@Override
	public void cleanCache() {
		healthHeadlineRepository.cleanCache();
	}

	
}















